package com.okilo.online.app.fmt

import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.okilo.online.app.R
import com.okilo.online.app.act.OkiloAdviceTypeAct
import com.okilo.online.app.act.OkiloUserLoginAct
import com.okilo.online.app.common.OkiloComFmt
import com.okilo.online.app.databinding.OkiloFmtStatusBinding
import com.okilo.online.app.event.OkiloEventData
import com.okilo.online.app.event.OkiloEventPointType
import com.okilo.online.app.tools.OkiloDensityUtil
import com.okilo.online.app.tools.apt.OkiloOnSingleClickListener
import com.okilo.online.app.tools.decoration.LinearSpacingItemDecoration
import com.okilo.online.app.tools.extensions.addCommasFromEndRegex
import com.okilo.online.app.tools.helper.OkiloConfigCustomerHp
import com.okilo.online.app.tools.helper.OkiloConfigProcessHp
import com.okilo.online.app.tools.helper.OkiloScoreDialogHp
import com.okilo.online.app.tools.shared.OkiloSharedHp
import com.okilo.online.app.apt.OkiloStatusDetailsWalletApt
import com.okilo.online.app.dialog.OkiloClearDataDlog
import com.okilo.online.app.dialog.OkiloTipsDlog
import com.okilo.online.app.pet.OkiloConfigsPet
import com.okilo.online.app.pet.OkiloLoanPet
import com.okilo.online.app.pet.OkiloUserPet
import com.okilo.online.app.pet.view.IOkiloConfigs
import com.okilo.online.app.pet.view.IOkiloLoan
import com.okilo.online.app.pet.view.IOkiloUser
import org.json.JSONObject
import java.math.BigDecimal

/**
 * OkiloLoan
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：首页 申贷状态：审核中、放款中、已拒绝
 */
class OkiloHomeApplyStatusFmt : OkiloComFmt(), IOkiloUser.IOkiloDeleteUserData, IOkiloLoan.IOkiloOrderInfo,
    IOkiloUser.IOkiloUserWallet, IOkiloConfigs.IOkiloConfigScore {
    private var _binding: OkiloFmtStatusBinding? = null
    private var deleteDataAfterDate = ""
    private var walletAdapter: OkiloStatusDetailsWalletApt? = null

    //公告提示
    private var noticeDialog: OkiloTipsDlog? = null

    //用户Presenter
    private var userPet: OkiloUserPet? = null
    //贷款
    private var loanPet: OkiloLoanPet? = null
    //评分配置
    private var configsPet: OkiloConfigsPet? = null

    override var pageName: String = ""

    override val enablePageTrack: Boolean = false

    override fun createOkiloContentView(inflater: LayoutInflater): View? {
        _binding = OkiloFmtStatusBinding.inflate(layoutInflater)
        return _binding?.root
    }

    override fun initializeOkiloViews() {
        _binding?.okiloOrderStatusRefreshLayout?.setColorSchemeResources(R.color.okilo_color_theme, R.color.okilo_color_ff6200ee)

        initOkiloApplyDetailsWalletListView()
        _binding?.okiloOrderStatusContentLayout?.visibility = View.GONE
        _binding?.okiloOrderStatusWalletLayout?.visibility = View.GONE
    }

    override fun setupOkiloEventListeners() {
        _binding?.okiloOrderStatusRefreshLayout?.setOnRefreshListener {
            publishEventData(OkiloEventData(OkiloEventData.TYPE.OKILO_PROCESS_REFRESH))
        }

        //意见反馈
        _binding?.okiloOrderStatusButtonFeedback?.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                onIntent(OkiloAdviceTypeAct::class.java)
            }
        })
        //删除用户数据
        _binding?.okiloOrderStatusButtonDataDelete?.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.USER_DATA_CLEAR,pageName)
                sOkiloApplyStatusClearDataDialog()
            }
        })
    }

    override fun loadOkiloData() {
        if (loanPet == null){
            loanPet = OkiloLoanPet(this)
        }
        if (userPet == null){
            userPet = OkiloUserPet(this)
        }
        showOkiloLoading()
        onOkiloHomeApplyStatusRefreshData()
    }

    /**
     * 刷新数据
     */
    fun onOkiloHomeApplyStatusRefreshData(){
        //审核中 || 放款中 || 已拒绝
        val isReviewing = OkiloConfigProcessHp.iOkiloApplyReviewing()
        val isDisbursing = OkiloConfigProcessHp.iOkiloApplyDisbursing()
        val isRejected = OkiloConfigProcessHp.iOkiloApplyRejected()
        if (isReviewing or isDisbursing or isRejected){
            //获取贷款订单信息
            loanPet?.gOkiloApplyOrderDetailsRequest(this)
        }

        _binding?.okiloOrderStatusContentLayout?.visibility = View.VISIBLE
        //审核中
        if (isReviewing){
            addEventPointRequestAction(OkiloEventPointType.OKILO_PAGE_TRACK.LOAN_REVIEWING_START)
            sOkiloApplyStatusReviewingView()
            return
        }
        //放款中
        if (isDisbursing){
            addEventPointRequestAction(OkiloEventPointType.OKILO_PAGE_TRACK.LOAN_DISBURSING_START)
            sOkiloApplyStatusDisbursingView()
            return
        }
        //已拒绝
        if (isRejected){
            addEventPointRequestAction(OkiloEventPointType.OKILO_PAGE_TRACK.LOAN_REJECTED_START)
            sOkiloApplyStatusRejectedView()
            return
        }

        //待还款
//        publishEventData(OkiloEventData(OkiloEventData.TYPE.OKILO_SHOW_REPAY))
    }

    /**
     * 初始化Views
     */
    private fun initOkiloApplyDetailsWalletListView(){
        val binding = _binding ?: return
        binding.okiloOrderStatusWalletListView.isNestedScrollingEnabled = false
        binding.okiloOrderStatusWalletListView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(requireContext())
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.okiloOrderStatusWalletListView.layoutManager = layoutManager
        val topDecoration = OkiloDensityUtil.dp2px(12f)
        binding.okiloOrderStatusWalletListView.addItemDecoration(
            LinearSpacingItemDecoration(
                0,
                0,
                topDecoration,
                topDecoration
            )
        )
        walletAdapter = OkiloStatusDetailsWalletApt(binding.okiloOrderStatusWalletListView)
        binding.okiloOrderStatusWalletListView.adapter = walletAdapter
        binding.okiloOrderStatusWalletListView.itemAnimator = DefaultItemAnimator()
    }

    /**
     * 设置贷款信息
     */
    override fun sOkiloApplyOrderInfo(data: JSONObject){
        _binding?.okiloOrderStatusLoanAmountText?.text = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString().addCommasFromEndRegex()
        _binding?.okiloOrderStatusLoanTermText?.text = String.format(getString(R.string.okilo_order_status_loan_days),data.optString("days"))

        //审核中 || 放款中
        val isReviewing = OkiloConfigProcessHp.iOkiloApplyReviewing()
        val isDisbursing = OkiloConfigProcessHp.iOkiloApplyDisbursing()
        if (isReviewing or isDisbursing){
            //加载收款账户列表
            userPet?.gOkiloUserApplyStatusDetailsWalletListRequest(this)
            return
        }

        //已拒绝
        val isRejected = OkiloConfigProcessHp.iOkiloApplyRejected()
        if (isRejected){
            //获取是否显示清除用户数据按钮
            userPet?.gOkiloUserClearDataRequest(true,this)
        }
    }

    /**
     * 审核中
     */
    private fun sOkiloApplyStatusReviewingView(){
        pageName = "Reviewing_Page"
        _binding?.okiloOrderStatusIcon?.setImageResource(R.mipmap.okilo_order_status_reviewing_icon)

        val showKey = getString(R.string.okilo_order_status_reviewing_2)
        val showText = String.format(getString(R.string.okilo_order_status_reviewing_1),showKey)
        val startIndex = showText.indexOf(showKey)
        val spannable = SpannableString(showText)
        spannable.setSpan(ForegroundColorSpan(getColor(R.color.okilo_color_ffec273a)), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
//        spannable.setSpan(StyleSpan(Typeface.BOLD), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.okiloOrderStatusInReviewApproveText?.setTextColor(getColor(R.color.okilo_color_ff191919))
        _binding?.okiloOrderStatusInReviewApproveText?.text = spannable
        _binding?.okiloOrderStatusInReviewApproveText?.visibility = View.VISIBLE
        _binding?.okiloOrderStatusInReviewTipsText?.text = getString(R.string.okilo_order_status_reviewing_3)
        _binding?.okiloOrderStatusInReviewTipsText?.visibility = View.VISIBLE
        _binding?.okiloOrderStatusLable?.setImageResource(R.mipmap.okilo_order_status_in_reviewing)
        _binding?.okiloOrderStatusText?.text = getString(R.string.okilo_order_status_reviewing)
        _binding?.okiloOrderStatusReapplyAfterText?.visibility = View.GONE
        _binding?.okiloOrderStatusWalletTipsText?.text = getString(R.string.okilo_order_status_reviewing_5)
        _binding?.okiloOrderStatusWalletTipsText?.visibility = View.VISIBLE
        _binding?.okiloOrderStatusWalletListView?.visibility = View.VISIBLE
        _binding?.okiloOrderStatusButtonFeedback?.visibility = View.GONE
        _binding?.okiloOrderStatusButtonDataDelete?.visibility = View.GONE
        sOkiloNoticeDialog()
        //获取评分配置 (只有审核中 || 放宽中会处理)
        gOkiloApplyStatusDetailsScoreAction()
    }

    /**
     * 放款中
     */
    private fun sOkiloApplyStatusDisbursingView(){
        pageName = "Disbursing_Page"
        _binding?.okiloOrderStatusIcon?.setImageResource(R.mipmap.okilo_order_status_disbursing_icon)

        _binding?.okiloOrderStatusInReviewApproveText?.visibility = View.GONE
        _binding?.okiloOrderStatusInReviewTipsText?.visibility = View.GONE
        _binding?.okiloOrderStatusLable?.setImageResource(R.mipmap.okilo_order_status_payment_in_progress)
        _binding?.okiloOrderStatusText?.text = getString(R.string.okilo_order_status_disbursing)
        _binding?.okiloOrderStatusReapplyAfterText?.visibility = View.GONE
        _binding?.okiloOrderStatusWalletTipsText?.text = getString(R.string.okilo_order_status_reviewing_5)
        _binding?.okiloOrderStatusWalletTipsText?.visibility = View.VISIBLE
        _binding?.okiloOrderStatusWalletListView?.visibility = View.VISIBLE
        _binding?.okiloOrderStatusButtonFeedback?.visibility = View.GONE
        _binding?.okiloOrderStatusButtonDataDelete?.visibility = View.GONE
        sOkiloNoticeDialog()
        //获取评分配置 (只有审核中 || 放宽中会处理)
        gOkiloApplyStatusDetailsScoreAction()
    }

    /**
     * 已拒绝
     */
    private fun sOkiloApplyStatusRejectedView(){
        pageName = "Rejected_Page"
        _binding?.okiloOrderStatusIcon?.setImageResource(R.mipmap.okilo_order_status_rejected_icon)

        _binding?.okiloOrderStatusInReviewApproveText?.visibility = View.GONE
        _binding?.okiloOrderStatusInReviewTipsText?.visibility = View.GONE
        _binding?.okiloOrderStatusLable?.setImageResource(R.mipmap.okilo_order_status_rejected)
        _binding?.okiloOrderStatusText?.text = getString(R.string.okilo_order_status_rejected)
        _binding?.okiloOrderStatusReapplyAfterText?.text = String.format(getString(R.string.okilo_order_status_rejected_reapply_after), OkiloConfigProcessHp.gOkiloAgainApplyDate())
        _binding?.okiloOrderStatusReapplyAfterText?.visibility = View.VISIBLE
        _binding?.okiloOrderStatusWalletTipsText?.visibility = View.GONE
        _binding?.okiloOrderStatusWalletListView?.visibility = View.GONE
        _binding?.okiloOrderStatusWalletLayout?.visibility = View.GONE
        _binding?.okiloOrderStatusButtonFeedback?.visibility = View.VISIBLE
        _binding?.okiloOrderStatusButtonDataDelete?.visibility = View.GONE
    }

    /**
     * 设置已帮卡列表
     */
    override fun sOkiloUserWalletList(walletList: ArrayList<JSONObject>) {
        _binding?.okiloOrderStatusWalletLayout?.visibility = View.VISIBLE
        walletAdapter?.data = walletList
    }

    /**
     * 已拒绝： 是否显示清除用户数据按钮
     */
    override fun sOkiloShowDeleteUserData(data: JSONObject) {
        if (data.optString("showDropButton","NO") == "YES"){
            _binding?.okiloOrderStatusButtonDataDelete?.visibility = View.VISIBLE
            deleteDataAfterDate = data.optString("againDate")
        } else {
            _binding?.okiloOrderStatusButtonDataDelete?.visibility = View.GONE
        }
    }

    /**
     * 已拒绝： 清除用户数据成功
     */
    override fun sOkiloDeleteUserDataSuccess() {
        //退出登录，需要移除用户保存的信息
        OkiloSharedHp.onOkiloAppOut()
        onIntent(OkiloUserLoginAct::class.java)
    }

    /**
     * 公告提示
     */
    private fun sOkiloNoticeDialog(){
        //需要检验手机号，不显示公告信息
        if (OkiloConfigProcessHp.iOkiloCheckSmsFlag() || OkiloConfigProcessHp.iOkiloCheckWhatsAppFlag()){
            return
        }
        // 检查是否可以显示公告提示 || 确保页面没有关闭
        if (!iOkiloShowNoticeDialog() || !isActive()) {
            return
        }

        val noticeInfo = OkiloConfigCustomerHp.tOkiloApplyNoticeInfo() ?: return
        // 更新显示次数
        OkiloConfigCustomerHp.showOkiloNoticeCount += 1
        noticeDialog = OkiloTipsDlog(
            requireContext(),
            pageName,
            object : OkiloTipsDlog.IOkiloTipsClickCallback {
                override fun onClick(view: View?) {
                    addEventPointRequestAction(
                        OkiloEventPointType.OKILO_CLICK_TRACK.NOTICE_CONFIRM,
                        pageName
                    )
                }
            })
        noticeDialog?.setOnDismissListener {

        }
        noticeDialog?.let { dialog ->
            dialog.setCancelable(true)
            dialog.setCanceledOnTouchOutside(true)
            dialog.show()
            dialog.iOkiloDlogTipsDoubleButton(false)
            dialog.sOkiloDlogTipsIconResource(R.mipmap.okilo_dlog_notice_icon)
            dialog.sOkiloDlogTipsTitleText(noticeInfo.optString("noticeTitle"))
            dialog.sOkiloDlogTipsMsgText(noticeInfo.optString("noticeText"))
            dialog.sOkiloDlogTipsButtonConfirmText(getString(R.string.okilo_btn_confirm))
        }
    }

    /**
     * 检查是否应该显示通知对话框
     */
    private fun iOkiloShowNoticeDialog(): Boolean {
        if (!OkiloConfigCustomerHp.iOkiloApplyNoticeShow()) {
            return false
        }

        val noticeInfo = OkiloConfigCustomerHp.tOkiloApplyNoticeInfo() ?: return false
        val showNum = noticeInfo.optInt("num", 1)
        val num = OkiloConfigCustomerHp.showOkiloNoticeCount

        if (num >= showNum) {
            return false
        }
        // 检查对话框是否已经在显示
        if (noticeDialog?.isShowing == true) {
            return false
        }
        return true
    }

    /**
     * 检查 Fragment 是否处于活跃状态
     */
    private fun isActive(): Boolean {
        return isAdded &&
                !isDetached &&
                activity != null &&
                !requireActivity().isFinishing &&
                !requireActivity().isDestroyed
    }


    /**
     * 清空用户数据dialog
     */
    private fun sOkiloApplyStatusClearDataDialog(){
        val clearDialog = OkiloClearDataDlog(
            requireContext(),
            pageName,
            object : OkiloClearDataDlog.IDialogCallback {
                override fun onUserDataClearConfirmClick() {
                    //删除用户数据
                    userPet?.gOkiloUserClearDataRequest(false, this@OkiloHomeApplyStatusFmt)
                }
            })
        clearDialog.setCancelable(true)
        clearDialog.setCanceledOnTouchOutside(true)
        clearDialog.show()
        clearDialog.sOkiloUserDataDeleteInfo(OkiloConfigCustomerHp.gOkiloDeleteUserDataDesc(),deleteDataAfterDate)
    }

    /**
     * 只有审核中或放款中需要调此接口
     * 获取评分配置
     */
    private fun gOkiloApplyStatusDetailsScoreAction() {
        if (configsPet == null){
            configsPet = OkiloConfigsPet(this)
        }
        configsPet?.gOkiloConfigScoreRequest(this)
    }

    /**
     * 获取评分配置成功
     */
    override fun sOkiloConfigScoreCallback(data: JSONObject) {
        OkiloScoreDialogHp.showStarDialog(requireContext(),data)
    }

    override fun onOkiloPublishEvent(event: OkiloEventData) {
        super.onOkiloPublishEvent(event)
        when(event.eventType){
            OkiloEventData.TYPE.OKILO_PROCESS_REFRESHED,
            OkiloEventData.TYPE.OKILO_DATA_REFRESH-> {//流程刷新完成
            }
            OkiloEventData.TYPE.OKILO_HTTP_REQUEST_ERROR -> {
                hideOkiloLoading()
            }
            else -> {
            }
        }
    }

    override fun hideOkiloLoading() {
        super.hideOkiloLoading()
        _binding?.okiloOrderStatusRefreshLayout?.isRefreshing = false
    }

    override fun onDestroyView() {
        super.onDestroyView()
        hideOkiloLoading()
        _binding = null
    }

    override fun onDestroy() {
        super.onDestroy()
        //审核中
        val isReviewing = OkiloConfigProcessHp.iOkiloApplyReviewing()
        if (isReviewing){
            addEventPointRequestAction(OkiloEventPointType.OKILO_PAGE_TRACK.LOAN_REVIEWING_END)
            return
        }
        //放款中
        val isDisbursing = OkiloConfigProcessHp.iOkiloApplyDisbursing()
        if (isDisbursing){
            addEventPointRequestAction(OkiloEventPointType.OKILO_PAGE_TRACK.LOAN_DISBURSING_END)
            return
        }
        //已拒绝
        val isRejected = OkiloConfigProcessHp.iOkiloApplyRejected()
        if (isRejected){
            addEventPointRequestAction(OkiloEventPointType.OKILO_PAGE_TRACK.LOAN_REJECTED_END)
            return
        }
    }
}